/**
 * Notes: 收藏模块业务逻辑
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2022-05-24 07:48:00 
 */

const BaseProjectService = require('./base_project_service.js');
const util = require('../../../framework/utils/util.js');
const LikeModel = require('../model/like_model.js');

class LikeService extends BaseProjectService {

/** 是否点赞 */
async isLike(userId, oid, type) {
	type = String(type);

	let PREFIX = type.toUpperCase();
	let name = type.toLowerCase();

	let Model = require('../model/' + name + '_model.js')

	let model = await Model.getOne(oid, PREFIX + '_LIKE_LIST');
	if (!model) return { isLike: 0 };

	let arr = model[PREFIX + '_LIKE_LIST'];
	return { isLike: arr.includes(userId) ? 1 : 0 };
}

/**
 * 更新某人点赞
 * @param {*} userId 
 * @param {*} oid 
 * @param {*} cancelIfExist  已点赞的情况下是否取消
 */
async updateLike(userId, oid, type) {
	type = String(type);

	let PREFIX = type.toUpperCase();
	let name = type.toLowerCase();

	let Model = require('../model/' + name + '_model.js')
	let model = await Model.getOne(oid, PREFIX + '_LIKE_LIST');
	if (!model) return { isLike: 0 };

	let arr = model[PREFIX + '_LIKE_LIST'];
	let flag = 0;
	if (arr.includes(userId)) {
		arr = arr.filter(item => item != userId);
		flag = 0;
	}
	else {
		arr.push(userId);
		flag = 1;
	}
	await Model.edit(oid, {
		[PREFIX + '_LIKE_LIST']: arr,
		[PREFIX + '_LIKE_CNT']: arr.length
	});

	return { isLike: flag };

}

/** 取消点赞 */
async cancelLike(userId, oid) {
	let where = {
		LIKE_OID: oid,
		LIKE_USER_ID: userId
	}
	let effect = await LikeModel.del(where);

	return {
		effect
	};
}

/** 我的点赞列表 */
async getMyLikeList(userId, {
	search, // 搜索条件 
	sortType, // 搜索菜单
	sortVal, // 搜索菜单
	orderBy, // 排序  
	page,
	size,
	isTotal = true,
	oldTotal = 0
}) {
	orderBy = orderBy || {
		'LIKE_ADD_TIME': 'desc'
	};
	let fields = 'LIKE_TITLE,LIKE_ADD_TIME,LIKE_OID,LIKE_TYPE,LIKE_PATH';

	let where = {};
	if (util.isDefined(search) && search) {
		where.LIKE_TITLE = {
			$regex: '.*' + search,
			$options: 'i'
		};
	}
	where.LIKE_USER_ID = userId;

	return await LikeModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);

}

}

module.exports = LikeService;